package rigo.ricard.pris.rs.ac.uns.dmi.geocode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
import org.primefaces.model.map.LatLng;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

public class GeocodeByLocation {

	private static final Log log = LogFactoryUtil.getLog(GeocodeByLocation.class);
	
	private static final String GOOGLE_MAPS_GEOCODE_API_URL_BEGIN = "http://maps.googleapis.com/maps/api/geocode/json?address=";
	//private static final String GOOGLE_MAPS_GEOCODE_API_URL_END = "&sensor=false&region=hu&components=country:HU&sensor=false";
	private static final String GOOGLE_MAPS_GEOCODE_API_URL_END = "&sensor=false&region=hu&sensor=false";
	
	public static LatLng getCordinatesByLocation(String location) {
		URL url = null;
		
		try {
			try {
				url = new URL(GOOGLE_MAPS_GEOCODE_API_URL_BEGIN + URLEncoder.encode(location, "UTF-8") + GOOGLE_MAPS_GEOCODE_API_URL_END);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			log.error("error creating url : "+e.getMessage());
		}
		BufferedReader reader = null;
		StringBuffer buffer = null;
		try {
			reader = new BufferedReader(new InputStreamReader(url.openStream()));
			buffer = new StringBuffer();
			int read;
			char[] chars = new char[1024];
			while ((read = reader.read(chars)) != -1)
				buffer.append(chars, 0, read);
		} catch (Exception e) {
			log.error("error opening json file for geocoding"+e.getMessage());
			return null;
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					log.error("error closing reader : "+e.getMessage());
					return null;
				}
		}
	
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(buffer.toString());
			JSONArray results = jsonObject.getJSONArray("results");
			JSONObject firstResult = results.getJSONObject(0);
			Double lat = firstResult.getJSONObject("geometry").getJSONObject("location").getDouble("lat");
			Double lng = firstResult.getJSONObject("geometry").getJSONObject("location").getDouble("lng");
			return new LatLng(lat, lng);
		} catch (JSONException e) {
			log.error("error in geocoding location from json : "+e.getMessage());
			return null;
		}
		
	}
}
